<template>
  <div 
    class="markdown-renderer" 
    :class="{ 'dark-mode': isDark }"
    v-html="renderedHtml"
  />
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import 'highlight.js/styles/github-dark.css'
import { useThemeStore } from '../stores/theme'

interface Props {
  content: string
  options?: {
    gfm?: boolean
    breaks?: boolean
    sanitize?: boolean
  }
}

const props = withDefaults(defineProps<Props>(), {
  content: '',
  options: () => ({
    gfm: true,
    breaks: true,
    sanitize: true
  })
})

const themeStore = useThemeStore()
const isDark = computed(() => themeStore.isDark)

// 配置marked
const configureMarked = () => {
  // 自定义渲染器
  const renderer = new marked.Renderer()
  
  // 自定义代码块渲染
  renderer.code = (code: string, lang: string | undefined) => {
    const language = lang || 'text'
    const validLanguage = hljs.getLanguage(language) ? language : 'text'
    const highlighted = hljs.highlight(code, { language: validLanguage }).value
    
    return `
      <div class="code-block">
        <div class="code-header">
          <span class="language-label">${language}</span>
          <button class="copy-btn" onclick="copyToClipboard(this)" data-code="${encodeURIComponent(code)}">
            📋 复制
          </button>
        </div>
        <pre class="hljs"><code>${highlighted}</code></pre>
      </div>
    `
  }
  
  // 自定义内联代码渲染
  renderer.codespan = (code: string) => {
    return `<code class="inline-code">${code}</code>`
  }
  
  // 自定义表格渲染
  renderer.table = (header: string, body: string) => {
    return `
      <div class="table-wrapper">
        <table class="markdown-table">
          <thead>${header}</thead>
          <tbody>${body}</tbody>
        </table>
      </div>
    `
  }
  
  // 自定义链接渲染
  renderer.link = (href: string, title: string | null, text: string) => {
    const titleAttr = title ? ` title="${title}"` : ''
    return `<a href="${href}" target="_blank" rel="noopener noreferrer"${titleAttr} class="markdown-link">${text}</a>`
  }
  
  // 自定义引用渲染
  renderer.blockquote = (quote: string) => {
    return `<blockquote class="markdown-blockquote">${quote}</blockquote>`
  }
  
  // 设置marked配置
  marked.setOptions({
    renderer,
    highlight: function(code: string, lang: string) {
      const language = hljs.getLanguage(lang) ? lang : 'plaintext'
      return hljs.highlight(code, { language }).value
    },
    langPrefix: 'hljs language-',
    pedantic: false,
    gfm: props.options.gfm,
    breaks: props.options.breaks
  })
}

// 渲染markdown内容
const renderedHtml = computed(() => {
  if (!props.content) return '<p class="empty-content">暂无内容</p>'
  
  try {
    return marked(props.content)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return `<p class="error-content">Markdown渲染失败: ${error}</p>`
  }
})

// 全局复制函数
const setupGlobalCopyFunction = () => {
  if (typeof window !== 'undefined') {
    (window as any).copyToClipboard = (button: HTMLElement) => {
      const code = decodeURIComponent(button.dataset.code || '')
      navigator.clipboard.writeText(code).then(() => {
        const originalText = button.textContent
        button.textContent = '✅ 已复制'
        setTimeout(() => {
          button.textContent = originalText
        }, 2000)
      }).catch(() => {
        button.textContent = '❌ 复制失败'
        setTimeout(() => {
          button.textContent = '📋 复制'
        }, 2000)
      })
    }
  }
}

onMounted(() => {
  configureMarked()
  setupGlobalCopyFunction()
})
</script>

<style scoped>
.markdown-renderer {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  line-height: 1.6;
  color: #2c3e50;
  background: transparent;
}

/* 深色模式 */
.markdown-renderer.dark-mode {
  color: #e6e6e6;
}

/* 标题样式 */
.markdown-renderer :deep(h1),
.markdown-renderer :deep(h2),
.markdown-renderer :deep(h3),
.markdown-renderer :deep(h4),
.markdown-renderer :deep(h5),
.markdown-renderer :deep(h6) {
  margin: 1.5em 0 0.5em 0;
  font-weight: 600;
  line-height: 1.3;
}

.markdown-renderer :deep(h1) {
  font-size: 2em;
  border-bottom: 2px solid #42b883;
  padding-bottom: 0.5em;
}

.markdown-renderer :deep(h2) {
  font-size: 1.5em;
  border-bottom: 1px solid #e1e1e1;
  padding-bottom: 0.3em;
}

.dark-mode :deep(h2) {
  border-bottom-color: #3d3d3d;
}

.markdown-renderer :deep(h3) {
  font-size: 1.25em;
}

/* 段落和文本 */
.markdown-renderer :deep(p) {
  margin: 1em 0;
}

.markdown-renderer :deep(strong) {
  font-weight: 600;
}

.markdown-renderer :deep(em) {
  font-style: italic;
}

/* 列表样式 */
.markdown-renderer :deep(ul),
.markdown-renderer :deep(ol) {
  margin: 1em 0;
  padding-left: 2em;
}

.markdown-renderer :deep(li) {
  margin: 0.25em 0;
}

.markdown-renderer :deep(ul li) {
  list-style-type: disc;
}

.markdown-renderer :deep(ol li) {
  list-style-type: decimal;
}

/* 代码块样式 */
.markdown-renderer :deep(.code-block) {
  margin: 1em 0;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e1e1e1;
}

.dark-mode :deep(.code-block) {
  border-color: #3d3d3d;
}

.markdown-renderer :deep(.code-header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5em 1em;
  background: #f8f9fa;
  border-bottom: 1px solid #e1e1e1;
  font-size: 0.85em;
}

.dark-mode :deep(.code-header) {
  background: #2d2d2d;
  border-bottom-color: #3d3d3d;
}

.markdown-renderer :deep(.language-label) {
  color: #666;
  font-family: 'Courier New', monospace;
  font-weight: 600;
}

.dark-mode :deep(.language-label) {
  color: #b3b3b3;
}

.markdown-renderer :deep(.copy-btn) {
  background: #42b883;
  color: white;
  border: none;
  padding: 0.25em 0.5em;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8em;
  transition: background 0.2s;
}

.markdown-renderer :deep(.copy-btn):hover {
  background: #369870;
}

.markdown-renderer :deep(pre) {
  margin: 0;
  padding: 1em;
  overflow-x: auto;
  background: #f8f9fa !important;
  font-size: 0.9em;
}

.dark-mode :deep(pre) {
  background: #1a1a1a !important;
}

/* 内联代码样式 */
.markdown-renderer :deep(.inline-code) {
  background: #f1f3f4;
  color: #d73a49;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
  font-family: 'Courier New', monospace;
}

.dark-mode :deep(.inline-code) {
  background: #2d2d2d;
  color: #f97583;
}

/* 表格样式 */
.markdown-renderer :deep(.table-wrapper) {
  overflow-x: auto;
  margin: 1em 0;
}

.markdown-renderer :deep(.markdown-table) {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  overflow: hidden;
}

.dark-mode :deep(.markdown-table) {
  border-color: #3d3d3d;
}

.markdown-renderer :deep(.markdown-table th),
.markdown-renderer :deep(.markdown-table td) {
  padding: 0.75em 1em;
  text-align: left;
  border-bottom: 1px solid #e1e1e1;
}

.dark-mode :deep(.markdown-table th),
.dark-mode :deep(.markdown-table td) {
  border-bottom-color: #3d3d3d;
}

.markdown-renderer :deep(.markdown-table th) {
  background: #f8f9fa;
  font-weight: 600;
}

.dark-mode :deep(.markdown-table th) {
  background: #2d2d2d;
}

.markdown-renderer :deep(.markdown-table tr:hover) {
  background: #f8f9fa;
}

.dark-mode :deep(.markdown-table tr:hover) {
  background: rgba(66, 184, 131, 0.1);
}

/* 链接样式 */
.markdown-renderer :deep(.markdown-link) {
  color: #42b883;
  text-decoration: underline;
  transition: color 0.2s;
}

.markdown-renderer :deep(.markdown-link):hover {
  color: #369870;
}

/* 引用样式 */
.markdown-renderer :deep(.markdown-blockquote) {
  margin: 1em 0;
  padding: 0.75em 1em;
  border-left: 4px solid #42b883;
  background: #f8f9fa;
  color: #666;
}

.dark-mode :deep(.markdown-blockquote) {
  background: #2d2d2d;
  color: #b3b3b3;
}

/* 分割线 */
.markdown-renderer :deep(hr) {
  margin: 2em 0;
  border: none;
  border-top: 2px solid #e1e1e1;
}

.dark-mode :deep(hr) {
  border-top-color: #3d3d3d;
}

/* 图片样式 */
.markdown-renderer :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 1em 0;
}

/* 空内容和错误内容样式 */
.markdown-renderer :deep(.empty-content),
.markdown-renderer :deep(.error-content) {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 2em;
}

.markdown-renderer :deep(.error-content) {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
  border: 1px solid rgba(245, 108, 108, 0.3);
  border-radius: 6px;
}
</style>